package com.woyao;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.LoginResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.RandomUtil;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;
import com.woyao.core.util.TimeCountUtil;

import java.io.IOException;

import retrofit2.Call;

public class ForgetPasswordActivity extends AppCompatActivity {
    private String code = null;
    private Button sendCode = null;
    private String lastMobile = null;
    private final static int MAX = 60;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true);
        this.setTitle("忘记密码");

        final Button register = (Button) findViewById(R.id.register);
        sendCode = (Button) findViewById(R.id.sendCode);

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });

        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCode();
            }
        });
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }

    private void sendCode() {
        code = RandomUtil.randomNumber(6);
        EditText username = (EditText) findViewById(R.id.username);
        if (StringUtil.isNullOrEmpty(username.getText().toString())) {
            username.setError("手机号必填");
            return;
        }
        if (username.length() != 11) {
            username.setError("手机号错误");
            return;
        }
        final String usernameText = username.getText().toString();
        //
        lastMobile = usernameText;
        TimeCountUtil timer = new TimeCountUtil(ForgetPasswordActivity.this, MAX * 1000, 1000, sendCode);
        timer.start();
        final EditText verifyCode = (EditText) findViewById(R.id.code);

        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.sendCode(usernameText, code);
                BaseResponse body;
                try {
                    body = responseCall.execute().body();
                    return body.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }

            }

            @Override
            protected void onPostExecute(final Boolean success) {

                if (success) {

                } else {
                    verifyCode.setError("验证码发送错误!");
                    //todo 测试代码

                }
                verifyCode.setHint(code);
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);
    }

    private void register() {
        EditText username = (EditText) findViewById(R.id.username);
        final EditText password = (EditText) findViewById(R.id.password);
        EditText verifyCode = (EditText) findViewById(R.id.code);

        if (StringUtil.isNullOrEmpty(username.getText().toString())) {
            username.setError("用户名必填");
            username.requestFocus();
            return;
        }
        if (lastMobile == null || !lastMobile.equals(username.getText().toString())) {
            username.setError("用户名错误");
            username.requestFocus();
            return;
        }
        if (StringUtil.isNullOrEmpty(password.getText().toString())) {
            password.setError("密码必填");
            password.requestFocus();
            return;
        }
        if (password.length() < 6) {
            password.setError("密码至少6位");
            password.requestFocus();
            return;
        }
        if (StringUtil.isNullOrEmpty(verifyCode.getText().toString())) {
            verifyCode.setError("验证码必填");
            verifyCode.requestFocus();
            return;
        }
        if (code == null || !code.equals(verifyCode.getText().toString())) {
            verifyCode.setError("验证码错误");
            verifyCode.requestFocus();
            return;
        }
        final String usernameText = username.getText().toString();
        final String passwordText = password.getText().toString();
        AsyncTask<Void, Void, Boolean> task =
                new AsyncTask<Void, Void, Boolean>() {
                    private int userId;

                    @Override
                    protected Boolean doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<BaseResponse> call = svc.resetPassword(usernameText, passwordText);
                        try {
                            BaseResponse body = call.execute().body();
                            if (body.isSuccess()) {
                                Call<LoginResponse> loginResponseCall = svc.login(usernameText, passwordText);
                                LoginResponse loginResponse = loginResponseCall.execute().body();
                                userId = loginResponse.getUserId();
                                return loginResponse.isSuccess();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }

                    @Override
                    protected void onPostExecute(final Boolean success) {

                        if (success) {
                            Intent intent = new Intent();
                            intent.setClass(ForgetPasswordActivity.this, ChanceActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            finish();
                            LoginActivity.setLogin(getApplication(), usernameText, userId);
                            startActivity(intent);
                        } else {
                            password.setError("用户名或者密码错误");
                            password.requestFocus();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                    }
                };
        task.execute((Void) null);

    }
}
